# -*- coding: utf-8 -*-
"""
@Author: thekernel
@Date: 2020/6/22 20:31
@Description: 豆果美食 爬虫类
"""
import requests
from multiprocessing import Queue
from mongo_client import mongo


def handle_request(url, data):
    headers = {
        "client": "4",
        "version": "6920.4",
        "device": "SM-G9350",
        "sdk": "22,5.1.1",
        "imei": "861373280750547",
        "channel": "qqkp",
        "resolution": "1024*576",
        "dpi": "1.19375",
        "brand": "samsung",
        "scale": "1.19375",
        "timezone": "28800",
        "language": "zh",
        "cns": "3",
        "user-agent": "Mozilla/5.0 (Linux; Android 5.1.1; SM-G9350 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko)"
                      " Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36",
        "reach": "1",
        "newbie": "1",
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
        "Accept-Encoding": "gzip, deflate",
        "Host": "api.douguo.net",
        "Connection": "keep-alive"
    }
    response = requests.post(url=url, headers=headers, data=data)
    return response


def handle_recipe_list(data):
    """
    请求具体食材的做法
    :param data:
    :return:
    """
    print("当前处理的食材是:", data['keyword'])
    # 翻页
    for i in range(1, 11):
        recipe_list_url = 'http://api.douguo.net/recipe/v2/search/{0}/20'.format(str(i * 20))
        recipe_list_response = handle_request(url=recipe_list_url, data=data)
        recipe_list_dict = recipe_list_response.json()
        # 判断是否有数据
        if recipe_list_dict['result']['end'] == 1:
            break
        for item in recipe_list_dict['result']['list']:
            recipe_info = {'ingredients': data['keyword']}
            if item['type'] == 13:
                recipe_info['user_name'] = item['r']['an']
                recipe_info['ingredients_id'] = item['r']['id']
                recipe_info['describe'] = item['r']['cookstory'].replace('/n', '').replace(' ', '')
                recipe_info['recipe_name'] = item['r']['n']
                recipe_info['condiment_list'] = item['r']['major']
                # 获取详情页的内容
                detail_url = 'http://api.douguo.net/recipe/detail/' + str(recipe_info['shicai_id'])
                detail_data = {
                    "client": "4",
                    "author_id": "0",
                    "_vs": "2803",
                    "_ext": '{"query": {"kw": ' + recipe_info[
                        'ingredients'] + ', "src": "2803", "idx": "1", "type": "13", "id": ' + str(
                        recipe_info['ingredients_id']) + '}}'
                }
                detail_response = handle_request(url=detail_url, data=detail_data)
                detail_response_dict = detail_response.json()
                recipe_info['tips'] = detail_response_dict['result']['recipe']['tips']
                recipe_info['cook_step'] = detail_response_dict['result']['recipe']['cookstep'].strip()
                print('当前入库的是：', recipe_info['recipe_name'])
                mongo.inset_item(recipe_info)
            else:
                continue


class DouGuo(object):
    def __init__(self):
        self.queue_list = Queue()

    def handle_index(self):
        """
        请求食谱首页
        """
        url = 'http://api.douguo.net/recipe/flatcatalogs'
        data = {
            "client": "4",
            "_vs": "2305"
        }
        response_index = handle_request(url, data)
        index_response_dict = response_index.json()
        for index_item in index_response_dict['result']['cs']:
            for items in index_item['cs']:
                for item in items['cs']:
                    data2 = {
                        "client": "4",
                        "keyword": item['name'],
                        "order": "3",
                        "_vs": "400"
                    }
                    self.queue_list.put(data2)
